package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsService;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodsMemberDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.MemberGoodDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.offer.FeeTypeDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.OptionalAdditionalOfferModuleVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneProductModuleVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ServiceOfferInfoModuleVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.CuccServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.StrTools;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CuccOfferMemberCache;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CuccOfferOriginalInfoCache;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferRelCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdFeeCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferRelInfo;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.*;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;
import com.ztesoft.bss.base.staticdata.CoreDataOffer;
import com.ztesoft.bss.common.util.ContextUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <Description> <br>
 * 联通可选类型可选包组件处理类
 *
 * @author zhu.zixin<br>
 * @version 1.0<br>
 * @since R9.0<br>
 */
@Service
public class OptionalAdditionalOfferModuleHandler extends AbstractModuleHandler {

    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    private IGoodsService goodsService;

    @Override
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {
        ServiceOfferInfoModuleVO serviceOfferInfoModel = ((SceneNewOfferSeneVO) context.getSceneVo()).getServiceOfferInfoModuleVO();

        String sceneInstId = context.getSceneVo().getSceneInstId();
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = kiteSceneInst.getServiceOfferId();
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(context.getAcceptRequest().getCustId(), kiteSceneInst.getRootInstId());
        String bizType = querySceneInstService.getExtParameterValue(sceneInstId, "bizType");
        String cateId = "";
        if (!KiteObjectUtils.isEmpty(offerInst)) {
            cateId = offerInst.getAttrValue("cateId");
        }
        boolean isPrview = false ;
        // 业务变更存在操作类型模块的，则资费不能编辑
        if (Objects.nonNull(serviceOfferInfoModel) && KiteListUtils.isNotEmpty(serviceOfferInfoModel.getServiceOfferTypes())) {
            isPrview = true ;
        }
        // 五大双线 + 五大双线落地产品分类ID
        String[] cateIdArr = getCateIdForDoubleLine();
        //核查追单不允许新增资费
        if(KiteStringUtils.equalsAny(cateId, cateIdArr)&&KiteStringUtils.equals("1014", serviceOfferId)&&KiteStringUtils.equals("1012", bizType)){
            return null;
        }

        Map<String, OptionalAdditionalOfferModuleVO> additionalOfferModuleVO = getOptionalAdditionalOfferModuleVO(sceneInstId, isPrview);

        SceneProductModuleVO sceneFeeInfoVo = ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO();

        sceneFeeInfoVo.setAdditionalOffers(additionalOfferModuleVO);

        List<OptionalAdditionalOfferModuleVO> additionalOfferModuleVOList = new ArrayList<>();

        for (Map.Entry<String, OptionalAdditionalOfferModuleVO> entry : additionalOfferModuleVO.entrySet()) {
            // 批量受理部分环节，不允许编辑
            if (BatchAcceptUtil.isBatchNode(sceneInstId) || BatchAcceptUtil.batchNodeResetIsEdit(sceneInstId)) {
                entry.getValue().setIsEdit("F");
            }
            additionalOfferModuleVOList.add(entry.getValue());
        }
        return additionalOfferModuleVOList;
    }

    @Override
    public List<? extends ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {

        Map<String, OptionalAdditionalOfferModuleVO> additionalOfferModuleVOMap = new HashMap<>();
        List<OptionalAdditionalOfferModuleVO> additionalOfferModuleVOList = new ArrayList<>();
        //所有的主套餐
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        List<KiteOfferInst> offerInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String[] cateIdArr = getCateIdForDoubleLine();
        String[] zwyCate = getCateIdForZWY();

        // 五大双线附加商品，根据附加商品顺序，设置资费的orderId
        List<MemberGoodDTO> memberGoods = null;
        String orderId;
        KiteInst kiteInst = querySceneInstService.getKiteInst(sceneInst.getCustId(), sceneInst.getRootInstType(), sceneInst.getRootInstId());
        String catagoryId = OfferCache.get(kiteInst.getSpecId()).getCateId();
        if(KiteStringUtils.equalsAny(catagoryId, cateIdArr)) {
            String offerId = kiteInst.getSpecId();
            List<GoodsMemberDTO> offerMembers = CuccOfferMemberCache.get(offerId, ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
            if(offerMembers != null && offerMembers.size() > 0) {
                memberGoods = offerMembers.get(0).getMemberGoods();
            }
        }

        for (KiteOfferInst kiteOfferInst : offerInsts) {
            String cateId = Optional.ofNullable(kiteOfferInst.getAttr("cateId")).map(KiteAttr::getDefaultValue).orElse("");
            // 附属产品变更，不展示主产品的资费
            if (!GoodsInfoTransfer.isAddRoleOffer(kiteOfferInst.getSpecId(), cateId) && KiteStringUtils.isEqual(sceneInst.getServiceOfferId(), CuccServiceOfferConsts.SERVICE_OFFER_ADD_PRODUCT_CHANGE)) {
                continue;
            }

            List<KiteOfferInst> additionalOfferInsts = querySceneInstService.listAdditionalOfferInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteOfferInst.getOfferInstId());
            if (KiteListUtils.isNotEmpty(additionalOfferInsts)) {
                OptionalAdditionalOfferModuleVO additionalOfferModuleVO = new OptionalAdditionalOfferModuleVO();

                // 发起方资费
                List<KiteOfferInst> additionalOfferInsts1;
                // 收费方资费
                List<KiteOfferInst> additionalOfferInsts2 = null;
                if(ProdCateUtil.getDoubleLineOfferId().contains(kiteOfferInst.getOfferId())) {
                    List<FeeTypeDTO> feeTypes = new ArrayList<>();
                    FeeTypeDTO feeTypeDTO = new FeeTypeDTO();
                    feeTypeDTO.setFeeTypeCode("1");
                    feeTypeDTO.setFeeTypeName("发起方资费");
                    feeTypes.add(feeTypeDTO);
                    // 五大双线基础产品，获取【是否多方收费】=是
                    KiteProdInst kiteProdInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteOfferInst.getOfferInstId()).get(0);
                    if(KiteStringUtils.isEqual(kiteProdInst.getAttrValue("210008004"), "1_0000106")) {
                        feeTypeDTO = new FeeTypeDTO();
                        feeTypeDTO.setFeeTypeCode("2");
                        feeTypeDTO.setFeeTypeName("收费方资费");
                        feeTypes.add(feeTypeDTO);
                    }
                    additionalOfferModuleVO.setFeeTypes(feeTypes);

                    additionalOfferInsts1 = additionalOfferInsts.stream().filter(offerInst -> {
                        Map<String, Object> offerMap = ProdFeeCache.get(offerInst.getOfferId()).getOfferMap();
                        String payType = KiteMapUtils.getString(offerMap, "payType");
                        return !KiteStringUtils.equalsAny(payType, "monthly-charge", "one-time-charge");
                    }).collect(Collectors.toList());
                    additionalOfferInsts2 = additionalOfferInsts.stream().filter(offerInst -> {
                        Map<String, Object> offerMap = ProdFeeCache.get(offerInst.getOfferId()).getOfferMap();
                        String payType = KiteMapUtils.getString(offerMap, "payType");
                        return KiteStringUtils.equalsAny(payType, "monthly-charge", "one-time-charge");
                    }).collect(Collectors.toList());
                } else {
                    additionalOfferInsts1 = additionalOfferInsts;
                }

                DealAdditionalOfferInst(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts1, true, null, "1");
                if(KiteListUtils.isNotEmpty(additionalOfferInsts2)) {
                    DealAdditionalOfferInst(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts2, true, null, "2");
                }
                if ((KiteStringUtils.equalsAny(cateId, cateIdArr) && KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(),"1","2826"))
                    ||(KiteStringUtils.equalsAny(cateId,zwyCate)&&KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(),"1009"))
                    || ifShowFeeStatistics(cateId, sceneInst.getServiceOfferId())) {
                    if(!KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())){
                        dealStatisticsTableData(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts1, true, null, "1");
                    }

                    if(KiteListUtils.isNotEmpty(additionalOfferInsts2)) {
                        if(!KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())) {
                            dealStatisticsTableData(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts2, true, null, "2");
                        }
                    }
                }
                if (GoodsInfoTransfer.isAddRoleOffer(kiteOfferInst.getSpecId(), cateId)) {
                    additionalOfferModuleVO.setAddFee(true);
                }
                orderId = getMemberOrderId(memberGoods, kiteOfferInst.getOfferId());
                if(KiteStringUtils.isNotEmpty(orderId)) {
                    additionalOfferModuleVO.setOrderId(orderId);
                }
                additionalOfferModuleVO.setOfferInstId(kiteOfferInst.getOfferInstId());
                additionalOfferModuleVO.setOfferName(OfferCache.get(kiteOfferInst.getOfferId()).getOfferName());
                additionalOfferModuleVO.setOfferInstId(kiteOfferInst.getOfferInstId());
                additionalOfferModuleVO.setPreviewFlag(true);
                additionalOfferModuleVOMap.put(kiteOfferInst.getOfferInstId(), additionalOfferModuleVO);
                additionalOfferModuleVOList.add(additionalOfferModuleVO);
            }

        }
        SceneProductModuleVO sceneFeeInfoVo = ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO();
        sceneFeeInfoVo.setAdditionalOffers(additionalOfferModuleVOMap);
        return additionalOfferModuleVOList;
    }

    public Map<String, OptionalAdditionalOfferModuleVO> getOptionalAdditionalOfferModuleVO(String sceneInstId, boolean isPrivew) {

        Map<String, OptionalAdditionalOfferModuleVO> additionalOfferModuleVOMap = new HashMap<>();
        // 批量受理当前修改销售品实例标识，存在则说明是批量受理的单个修改场景
        String curOfferInstId = querySceneInstService.getExtParameterValue(sceneInstId, "curOfferInstId");
        // 趸交支付详情场景
        String payDetailFlag = querySceneInstService.getExtParameterValue(sceneInstId, "PAY_DETAIL_FLAG");
        //所有的主套餐
        List<KiteOfferInst> offerInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        // 批量受理的单个修改，只处理当前修改的销售品实例
        if (KiteStringUtils.isNotEmpty(curOfferInstId)) {
            offerInsts.removeIf(offerInstDTO -> !KiteStringUtils.isEqual(offerInstDTO.getOfferInstId(),
                curOfferInstId));
        }
        else if (CuccPosServiceUtils.isBatchAccept(sceneInstId) || BatchAcceptUtil.isBatchSign(sceneInstId)) {
            // 批量受理录入页面、批量签订，只展示根节点的资费
            offerInsts.removeIf(
                offerInstDTO -> !KiteStringUtils.isEqual(offerInstDTO.getOfferInstId(), sceneInst.getRootInstId()));
        }

        // 五大双线 + 五大双线落地产品分类ID
        String[] cateIdArr = getCateIdForDoubleLine();
        String[] zwyCate = getCateIdForZWY();

        // 五大双线附加商品，根据附加商品顺序，设置资费的orderId
        List<MemberGoodDTO> memberGoods = Lists.newArrayList();
        String orderId;
        KiteInst kiteInst = querySceneInstService.getKiteInst(sceneInst.getCustId(), sceneInst.getRootInstType(), sceneInst.getRootInstId());
        String catagoryId = OfferCache.get(kiteInst.getSpecId()).getCateId();
        if(KiteStringUtils.equalsAny(catagoryId, cateIdArr)) {
            String offerId = kiteInst.getSpecId();
            List<GoodsMemberDTO> offerMembers = CuccOfferMemberCache.get(offerId, ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
            if(offerMembers != null && offerMembers.size() > 0) {
                offerMembers.forEach(offerMember -> memberGoods.addAll(offerMember.getMemberGoods()));
            }
        }
        String serviceOfferId = sceneInst.getServiceOfferId();
        for (KiteOfferInst kiteOfferInst : offerInsts) {
            String cateId = OfferCache.get(kiteOfferInst.getSpecId()).getCateId();;
            // 附属产品变更，不展示主产品的资费
            boolean addRoleOfferFlag = GoodsInfoTransfer.isAddRoleOffer(kiteOfferInst.getSpecId(), cateId);

            if (!addRoleOfferFlag && KiteStringUtils.isEqual(serviceOfferId, CuccServiceOfferConsts.SERVICE_OFFER_ADD_PRODUCT_CHANGE)) {
                continue;
            }
            // 主产品删除了，不加载
            if (KiteStringUtils.isEqual(kiteOfferInst.getActionType().name(), ActionType.D.name())) {
                continue;
            }
            //查询所有的可选包规格
            List<OfferRelInfo> offerRelInfoList = OfferRelCache.get(kiteOfferInst.getOfferId()).stream().filter(offerRelInfo -> {
                return CoreDataOffer.OFF_0005_12.equals(offerRelInfo.getzOfferType());
            }).collect(Collectors.toList());
            if (KiteListUtils.isEmpty(offerRelInfoList)) {
                continue;
            }
            OptionalAdditionalOfferModuleVO additionalOfferModuleVO = new OptionalAdditionalOfferModuleVO();
            additionalOfferModuleVO.setAddButton(true);
            if (addRoleOfferFlag) {
                additionalOfferModuleVO.setAddFee(true);
            }
            additionalOfferModuleVO.setOfferName(OfferCache.get(kiteOfferInst.getOfferId()).getOfferName());
            additionalOfferModuleVO.setOfferInstId(kiteOfferInst.getOfferInstId());
            orderId = getMemberOrderId(memberGoods, kiteOfferInst.getOfferId());
            if(KiteStringUtils.isNotEmpty(orderId)) {
                additionalOfferModuleVO.setOrderId(orderId);
            }
            List<KiteOfferInst> additionalOfferInsts = querySceneInstService.listAdditionalOfferInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteOfferInst.getOfferInstId());
            // 趸交支付详情界面只需要展示趸交资费信息，其他信息过滤
            if (KiteStringUtils.isNotEmpty(payDetailFlag) && KiteStringUtils.equals(payDetailFlag, KeyConsts.IFTRUE_T)) {
                additionalOfferInsts.removeIf(additionalOfferInst -> {
                    Map<String, Object> offerMap = Optional.ofNullable(ProdFeeCache.get(additionalOfferInst.getOfferId())).map(Offer::getOfferMap).orElse(null);
                    if (!LocalKeyConsts.FEE_PAY_TYPE_ONE_OFF.equals(KiteMapUtils.getString(offerMap, "payType"))) {
                        return true;
                    }
                    return false;
                });
            }

            if(ProdCateUtil.getDoubleLineOfferId().contains(kiteOfferInst.getOfferId())) {
                List<FeeTypeDTO> feeTypes = new ArrayList<>();
                FeeTypeDTO feeTypeDTO = new FeeTypeDTO();
                feeTypeDTO.setFeeTypeCode("1");
                feeTypeDTO.setFeeTypeName("发起方资费");
                feeTypes.add(feeTypeDTO);
                // 五大双线基础产品，获取【是否多方收费】=是
                List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteOfferInst.getOfferInstId());
                if(KiteListUtils.isNotEmpty(kiteProdInsts)) {
                    if(KiteStringUtils.isEqual(kiteProdInsts.get(0).getAttrValue("210008004"), "1_0000106")) {
                        feeTypeDTO = new FeeTypeDTO();
                        feeTypeDTO.setFeeTypeCode("2");
                        feeTypeDTO.setFeeTypeName("收费方资费");
                        feeTypes.add(feeTypeDTO);
                    }
                }
                additionalOfferModuleVO.setFeeTypes(feeTypes);
            }

            if (KiteListUtils.isNotEmpty(additionalOfferInsts)) {
                // 发起方资费
                List<KiteOfferInst> additionalOfferInsts1;
                // 收费方资费
                List<KiteOfferInst> additionalOfferInsts2 = null;
                if (KiteListUtils.isNotEmpty(additionalOfferModuleVO.getFeeTypes())) {
                    additionalOfferInsts1 = additionalOfferInsts.stream().filter(offerInst -> {
                        Map<String, Object> offerMap = ProdFeeCache.get(offerInst.getOfferId()).getOfferMap();
                        String payType = KiteMapUtils.getString(offerMap, "payType");
                        return !KiteStringUtils.equalsAny(payType, "monthly-charge", "one-time-charge");
                    }).collect(Collectors.toList());
                    additionalOfferInsts2 = additionalOfferInsts.stream().filter(offerInst -> {
                        Map<String, Object> offerMap = ProdFeeCache.get(offerInst.getOfferId()).getOfferMap();
                        String payType = KiteMapUtils.getString(offerMap, "payType");
                        return KiteStringUtils.equalsAny(payType, "monthly-charge", "one-time-charge");
                    }).collect(Collectors.toList());
                } else {
                    additionalOfferInsts1 = additionalOfferInsts;
                }

                // 资费详情
                DealAdditionalOfferInst(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts1, isPrivew, payDetailFlag, "1");
                if(KiteListUtils.isNotEmpty(additionalOfferInsts2)) {
                    DealAdditionalOfferInst(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts2, isPrivew, payDetailFlag, "2");
                }
                if ((KiteStringUtils.equalsAny(cateId, cateIdArr) && KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(),"1","2826","1014"))
                    ||(KiteStringUtils.equalsAny(cateId,zwyCate)&&KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(),"1009"))
                    || ifShowFeeStatistics(cateId, sceneInst.getServiceOfferId())) {
                    // 资费统计信息   五大双线不需要统计
                    if(!KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())){
                        dealStatisticsTableData(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts1, isPrivew, payDetailFlag, "1");
                    }
                    if(KiteListUtils.isNotEmpty(additionalOfferInsts2)) {
                        // 资费统计信息   五大双线不需要统计
                        if(!KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())){
                            dealStatisticsTableData(sceneInstId, kiteOfferInst, additionalOfferModuleVO, additionalOfferInsts2, isPrivew, payDetailFlag, "2");
                        }
                    }
                }
            }
            additionalOfferModuleVOMap.put(kiteOfferInst.getOfferInstId(), additionalOfferModuleVO);
        }
        return additionalOfferModuleVOMap;
    }

    private boolean filterOfferVoByKeyAttr(String cateId, List serviceOfferIdList, KiteOfferInst kiteOfferInst, KiteOfferInst additionalOfferInst) {
        boolean resultCode = true;
        boolean resultflag = false;
        //属性联动资费展示
        String code=DcPublicCache.getPCode("20210903104801", cateId);
        if(KiteStringUtils.equalsAny("T",code)&&KiteListUtils.isNotEmpty(serviceOfferIdList)){
            resultCode=false;
        }
        KiteProdInst kiteProdInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteOfferInst.getOfferInstId()).get(0);
        List<DcPublic> dpList = DcPublicCache.getByPkey("20210602110701", additionalOfferInst.getSpecId());
        if (KiteListUtils.isNotEmpty(dpList)&&KiteListUtils.isNotEmpty(serviceOfferIdList)) {//若存在配置则判断是否和关键实行一致 不存在返回true
            for (DcPublic dcPublic : dpList) {
                //dcPublic = dpList.get(0);offerid
                if (KiteStringUtils.isNotEmpty(dcPublic.getComments())) {
                    JSONObject cfgObj = JSON.parseObject(dcPublic.getComments());
                    for (JSONObject.Entry<String, Object> cfen : cfgObj.entrySet()) {
                        String[] cfenVal = JSON.parseArray(cfen.getValue().toString()).toArray(new String[]{});
                        if(KiteListUtils.isNotEmpty(serviceOfferIdList)){
                            resultCode = false;
                            if(serviceOfferIdList.contains(dcPublic.getCodec())){
                                if(((KiteStringUtils.equalsAny("*",cfenVal)&&!kiteProdInst.getAttrValue(cfen.getKey()).isEmpty())
                                    ||KiteStringUtils.equalsAny(kiteProdInst.getAttrValue(cfen.getKey()), cfenVal))){
                                    resultflag=true;
                                }else {
                                    resultflag=false;
                                }
                            }
                        }else{
                            if((KiteStringUtils.equalsAny("*",cfenVal)&&kiteProdInst.getAttrValue(cfen.getKey()).isEmpty())
                                ||!KiteStringUtils.equalsAny(kiteOfferInst.getAttrValue(cfen.getKey()), cfenVal)){
                                resultCode = false;
                            }
                        }
                    }
                }
                if(!resultCode&&resultflag){
                    resultCode=true;
                }
                return resultCode;
            }
        }
        return resultCode;
    }

    protected void DealAdditionalOfferInst(String sceneInstId, KiteOfferInst kiteOfferInst, OptionalAdditionalOfferModuleVO additionalOfferModuleVO, List<KiteOfferInst> additionalOfferInsts, boolean isPrivew, String payDetailFlag, String feeTypeCode) {
        List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");//获取页面勾选的操作类型
        // 获取能被分组的资费
        String feeGroupCategroys= feeProdIsToGroup(kiteOfferInst);
        // 临时调速场景
         String PAY_TIAOSU_FLAG = querySceneInstService.getExtParameterValue(sceneInstId, "PAY_TIAOSU_FLAG");
        //拼装表头
        List<Map> tableColList = new ArrayList();
        //描述字段组装
        List<String> feeDescribeFieldList = new ArrayList();
        //拼装表数据
        List<Map> tableValueList = new ArrayList();
        String cateId = kiteOfferInst.getAttrValue("cateId");
        String serviceOfferId = this.querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();
        getTableHeader(tableColList, cateId, feeDescribeFieldList);
        //先按照生效时间排序
        sortKitePosFeeList(additionalOfferInsts);
        //再按照销售品ID进行排序，行业5G资费只按照生效时间排序
        if (!KiteStringUtils.equals(cateId, "2000966")) {
            sortOfferList(additionalOfferInsts);
        }
        additionalOfferInsts.forEach(feeOfferInst ->{
            boolean flag=filterOfferVoByKeyAttr(cateId,serviceOfferIdList,kiteOfferInst,feeOfferInst);
            if(!flag&&"T".equals(PAY_TIAOSU_FLAG)){
                return;
            }
            Map tableValue = new HashMap();
            for(Map<String, String> tableCol : tableColList) {
                String key = tableCol.get("dataIndex");
                if (KiteStringUtils.isEqual(key,"ctrl")) {
                    continue;
                }
                if (KiteStringUtils.isEqual(key,"name")) {
                    tableValue.put(key, feeOfferInst.getOfferName());
                }
                else if (KiteStringUtils.isEqual(key,"feeDescribe")) {
                    StringBuffer feeDescribe = new StringBuffer();
                    for (String feeDescribeField :feeDescribeFieldList) {
                        if (!KiteStringUtils.isEqual(feeDescribeField, "name")) {
                            KiteAttr kiteAttr = feeOfferInst.getAttr(feeDescribeField);
                            if (Objects.nonNull(kiteAttr)) {
                                //协议月租
                                if("200000169".equals(feeDescribeField)||"210004920".equals(feeDescribeField)){
                                    tableValue.put(feeDescribeField, kiteAttr.getValue());
                                }
                                feeDescribe.append(kiteAttr.getCname()).append("=").append(getValue(kiteAttr)).append(";");
                            }
                        }
                    }
                    tableValue.put(key, feeDescribe.toString());
                }
                else if (KiteStringUtils.isEqual(key,"actionType")) {
                    tableValue.put(key, feeOfferInst.getActionType().name());
                }
                else {
                    KiteAttr kiteAttr = feeOfferInst.getAttr(key);
                    if(Objects.nonNull(kiteAttr)){
                        if(KiteStringUtils.isEqual(key,"200001352")){
                            //标准资费(元) //协议月租
                            String rentAgreementValue = getValue(feeOfferInst.getAttr("200000169"));
                            String standardFeeValue = getValue(feeOfferInst.getAttr("200001354"));
                            String discountRate="";
                            if(KiteStringUtils.isNotEmpty(rentAgreementValue) && KiteStringUtils.isNotEmpty(standardFeeValue)&& !KiteStringUtils.equalsAny("0",standardFeeValue)){
                                discountRate = StrTools.numDivide(rentAgreementValue, standardFeeValue,4);
                                BigDecimal discountRateNew = new BigDecimal(StrTools.numMultiply(discountRate,"100")).setScale(2, BigDecimal.ROUND_HALF_UP);
                                kiteAttr.setValue(discountRateNew+"%");
                            }
                        }
                        if(KiteStringUtils.isEmpty(kiteAttr.getValue())){
                            kiteAttr.setValue("");
                        }
                        tableValue.put(key, kiteAttr.getValue());
                    }
                }
            }
            // 趸交资费产品的标准月租  200002980 ；其它资费的标准月租 200001354
            if(!KiteObjectUtils.isEmpty(feeOfferInst.getAttr("200002980"))){
                //存在趸交资费产品的标准月租和 其它资费的标准月租编码不一致情况 但趸交的标准月租也要展示出来
                tableValue.put("200001354", feeOfferInst.getAttr("200002980").getValue());
            }
            //生效模式 200000174
            if(!KiteObjectUtils.isEmpty(feeOfferInst.getAttr("200000174"))){
                //生效模式是以起租时间生效也要进行分组
                tableValue.put("200000174", feeOfferInst.getAttr("200000174").getValue());
            }

            tableValue.put("offerInstId", feeOfferInst.getOfferInstId());
            Map<String, Object> offerMap = ProdFeeCache.get(feeOfferInst.getOfferId()).getOfferMap();
            String payType = KiteMapUtils.getString(offerMap, "payType");
            if (KiteMapUtils.isNotEmpty(offerMap)) {
                tableValue.put("payType", payType);
            }
            // 资费类型（1：发起发资费；2：收费方资费）
            tableValue.put("feeTypeCode", KiteStringUtils.equalsAny(payType, "monthly-charge", "one-time-charge")?"2":"1");
            if (!isPrivew) {
                ActionType action = feeOfferInst.getActionType();
                if (KiteStringUtils.isEqual(action.name(), ActionType.A.name())) {
                    // 趸交资费详情场景
                    if (KiteStringUtils.isNotEmpty(payDetailFlag) && KeyConsts.IFTRUE_T.equals(payDetailFlag)
                        || BatchAcceptUtil.batchNodeResetIsEdit(sceneInstId)) {
                        tableValue.put("delOfferInst", "false");
                        tableValue.put("modOfferInst", "false");
                    } else {
                        //资费产品实例为新增状态时，有删除和修改操作
                        tableValue.put("delOfferInst", "true");
                        tableValue.put("modOfferInst", "true");
                    }
                }
                else if (KiteStringUtils.isEqual(action.name(), ActionType.C.name())) {
                  //资费产品实例为作废状态时，有撤销操作
                    tableValue.put("revokeOfferInst", "true");
                }
                else {
                    // 存量一次性资费只允许查看，不允许删除，编辑
                    if (KiteStringUtils.equalsAny(payType, "one-time", "one-time-charge")) {
                        tableValue.put("modOfferInst", "false");
                    } else if (KiteStringUtils.equals("2000966", cateId) && KiteStringUtils.equals("2826", serviceOfferId)) {
                        // 行业5G新增资费 变更时资费不可编辑
                        tableValue.put("modOfferInst", "false");
                    } else {
                        //资费产品实例为不变、修改状态时，有修改操作
                        tableValue.put("modOfferInst", "true");
                    }
                    String startDate = getValue (feeOfferInst.getAttr("200000172"));
                    // 未生效的资费，可以作废
                    if (KiteStringUtils.isNotEmpty(startDate)
                        && DateFormatUtils.compareDate(DateFormatUtils.getFormatedDateTime(), startDate, DateFormatUtils.DATE_TIME_FORMAT)<0) {
                        tableValue.put("cancelOfferInst", "true");
                    }
                    // 生效模式
                    KiteAttr effectiveMode =feeOfferInst.getAttr("200000174");
                    if (Objects.nonNull(effectiveMode) && KiteStringUtils.isEqual(effectiveMode.getValue(), "110006909")) {
                        tableValue.put("200000174", getValue(effectiveMode));
                    }

                    // 失效模式
                    KiteAttr failureMode =feeOfferInst.getAttr("200001735");
                    if (Objects.nonNull(failureMode) && KiteStringUtils.isEqual(failureMode.getValue(), "110006910")) {
                        tableValue.put("200001735", getValue(failureMode));
                    }
                }
                if (LocalKeyConsts.FEE_PAY_TYPE_ONE_OFF.equals(payType)) {
                    this.dealOneOffAdditionalOffer(sceneInstId, tableValue, feeOfferInst);
                }
                // 5G行业消息资费变更当月资费无法失效规则
                if (KiteStringUtils.equals(cateId, "2000966") && KiteStringUtils.equals(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_FEE_MODIFY)) {
                    this.dealRcsAdditionalOffer(sceneInstId, tableValue, feeOfferInst);
                }
            }

            //五大双线 判断这条资费是否支持分组
            if(KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())){
                if(KiteStringUtils.isNotEmpty(feeGroupCategroys) && feeGroupCategroys.contains(feeOfferInst.getSpecId())){
                    tableValue.put("isShowGroup","true");
                }else {
                    tableValue.put("isShowGroup","false");
                }
            }
            tableValueList.add(tableValue);
        });
        Map tableFeeAttr = new HashMap();
        tableFeeAttr.put("tableCol", tableColList);
        tableFeeAttr.put("tableValue", tableValueList);

        // 五大双线新增一个分组展示资费列表统计功能 // 2004026光纤、2004017MV、2004029互联网、SDH:2004023、2004022、2004021、2004020、以太网：2004034、2004033、2004032、2004031
        //if(KiteStringUtils.equalsAny(cateId,"2004026","2004017","2004029","2004023","2004022","2004021","2004020","2004034","2004033","2004032","2004031")){
        if(KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())){
            if(!KiteStringUtils.isEqual(feeTypeCode, "2")){   //收费方资费不进行分组
                List<Map>  tableValueGroupList = addTableFeeValueAttrGroup(tableValueList);  //五大双线
                tableFeeAttr.put("tableValueGroup", JSON.toJSON(tableValueGroupList));
            }
        }
        if(KiteStringUtils.isEqual(feeTypeCode, "2")) {
            additionalOfferModuleVO.setTableChargeFeeAttr(tableFeeAttr);
        } else {
            additionalOfferModuleVO.setTableFeeAttr(tableFeeAttr);
        }
    }

    private void dealRcsAdditionalOffer(String sceneInstId, Map tableValue, KiteOfferInst feeOfferInst) {
        KiteAttr endDateAttr = feeOfferInst.getAttr(LocalKeyConsts.END_DATE_FIELD_NAME);
        // 存量数据当月资费无法失效规则
        if (ActionType.K.name().equals(feeOfferInst.getActionType().name()) && Objects.nonNull(endDateAttr) &&
            DateFormatUtils.compareDate(endDateAttr.getValue(), DateFormatUtils.getMinMonthDate(), DateFormatUtils.DATE_TIME_FORMAT) >= 0 &&
            DateFormatUtils.compareDate(endDateAttr.getValue(), DateFormatUtils.getMaxMonthDate(), DateFormatUtils.DATE_TIME_FORMAT) <= 0) {
            tableValue.remove("modOfferInst");
            tableValue.remove("delOfferInst");
        }
    }

    private void dealStatisticsTableData(String sceneInstId, KiteOfferInst kiteOfferInst, OptionalAdditionalOfferModuleVO additionalOfferModuleVO, List<KiteOfferInst> additionalOfferInsts, boolean isPrivew, String payDetailFlag, String feeTypeCode){
        List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");//获取页面勾选的操作类型
        // 临时调速场景
        String PAY_TIAOSU_FLAG = querySceneInstService.getExtParameterValue(sceneInstId, "PAY_TIAOSU_FLAG");
        //拼装表头
        List<Map> tableColList = new ArrayList();
        //拼装表数据
        List<Map> tableValueList = new ArrayList();
        String catId = kiteOfferInst.getAttrValue("cateId");
        getStatisticsTableHeader(tableColList, catId);
        //先按照生效时间排序
        sortKitePosFeeList(additionalOfferInsts);
        //再按照销售品ID进行排序
        sortOfferList(additionalOfferInsts);
        String countFee = "0";
        ArrayList<String> feeArray = new ArrayList<String> ();
        additionalOfferInsts.forEach(feeOfferInst ->{
            boolean flag=filterOfferVoByKeyAttr(catId,serviceOfferIdList,kiteOfferInst,feeOfferInst);
            // 作废的资费不计入总和
            if (ActionType.C.equals(feeOfferInst.getActionType())||(!flag&&"T".equals(PAY_TIAOSU_FLAG))) {
                return;
            }
            if (!"".equals(getValue(feeOfferInst.getAttr("210004920"))) ||!"".equals(getValue(feeOfferInst.getAttr("200001354"))) || !"".equals(getValue(feeOfferInst.getAttr("200000169")))) {
                Map tableValue = new HashMap();
                for(Map<String, String> tableCol : tableColList) {
                    String key = tableCol.get("dataIndex");
                    if (KiteStringUtils.isEqual(key,"ctrl")) {
                        continue;
                    }
                    if (KiteStringUtils.isEqual(key,"name")) {
                        tableValue.put(key, feeOfferInst.getOfferName());
                    }
                    else if (KiteStringUtils.isEqual(key,"off")) {
                        if (KiteStringUtils.equalsAny(getValue(feeOfferInst.getAttr("200001354")),"","0","暂无价格")) {
                            tableValue.put(key, "N/A");
                        } else if (KiteStringUtils.equalsAny(getValue(feeOfferInst.getAttr("200000169")),"","0")) {
                            tableValue.put(key, "N/A");
                        } else {
                            String discountRate = StrTools.numDivide(getValue(feeOfferInst.getAttr("200000169")), getValue(feeOfferInst.getAttr("200001354")),2);
                            discountRate = StrTools.numMultiply(discountRate,"100");
                            tableValue.put(key, discountRate+"%");
                        }
                    }
                    else {
                        KiteAttr kiteAttr = feeOfferInst.getAttr(key);
                        String fee = getValue(kiteAttr);
                        tableValue.put(key, fee);
                        //协议月租
                        if (KiteStringUtils.isEqual(key,"200000169") && !KiteStringUtils.isEqual(fee,"")) {
                            feeArray.add(getValue(kiteAttr));
                        }
                        //协议价格
                        if (KiteStringUtils.isEqual(key,"210004920") && !KiteStringUtils.isEqual(fee,"")) {
                            feeArray.add(getValue(kiteAttr));
                        }
                        // 存量资费标准资费统一展示成N/A
                        this.handleStandardFee(tableValue, feeOfferInst, key);
                    }
                }

                tableValue.put("offerInstId", feeOfferInst.getOfferInstId());
                Map<String, Object> offerMap = ProdFeeCache.get(feeOfferInst.getOfferId()).getOfferMap();
                String payType = KiteMapUtils.getString(offerMap, "payType");
                if (KiteMapUtils.isNotEmpty(offerMap)) {
                    tableValue.put("payType", payType);
                }
                if (!isPrivew) {
                    ActionType action = feeOfferInst.getActionType();
                    if (KiteStringUtils.isEqual(action.name(), ActionType.A.name())) {
                        // 趸交资费详情场景
                        if (KiteStringUtils.isNotEmpty(payDetailFlag) && KeyConsts.IFTRUE_T.equals(payDetailFlag)
                            || BatchAcceptUtil.batchNodeResetIsEdit(sceneInstId)) {
                            tableValue.put("delOfferInst", "false");
                            tableValue.put("modOfferInst", "false");
                        } else {
                            //资费产品实例为新增状态时，有删除和修改操作
                            tableValue.put("delOfferInst", "true");
                            tableValue.put("modOfferInst", "true");
                        }
                    }
                    else if (KiteStringUtils.isEqual(action.name(), ActionType.C.name())) {
                        //资费产品实例为作废状态时，有撤销操作
                        tableValue.put("revokeOfferInst", "true");
                    }
                    else {
                        // 存量一次性资费只允许查看，不允许删除，编辑
                        if (KiteStringUtils.equalsAny(payType, "one-time", "one-time-charge")) {
                            tableValue.put("modOfferInst", "false");
                        } else {
                            //资费产品实例为不变、修改状态时，有修改操作
                            tableValue.put("modOfferInst", "true");
                        }
                        String startDate = getValue (feeOfferInst.getAttr("200000172"));
                        // 未生效的资费，可以作废
                        if (KiteStringUtils.isNotEmpty(startDate)
                            && DateFormatUtils.compareDate(DateFormatUtils.getFormatedDateTime(), startDate, DateFormatUtils.DATE_TIME_FORMAT)<0) {
                            tableValue.put("cancelOfferInst", "true");
                        }
                        // 生效模式
                        KiteAttr effectiveMode =feeOfferInst.getAttr("200000174");
                        if (Objects.nonNull(effectiveMode) && KiteStringUtils.isEqual(effectiveMode.getValue(), "110006909")) {
                            tableValue.put("200000174", getValue(effectiveMode));
                        }

                        // 失效模式
                        KiteAttr failureMode =feeOfferInst.getAttr("200001735");
                        if (Objects.nonNull(failureMode) && KiteStringUtils.isEqual(failureMode.getValue(), "110006910")) {
                            tableValue.put("200001735", getValue(failureMode));
                        }
                    }
                    if (LocalKeyConsts.FEE_PAY_TYPE_ONE_OFF.equals(payType)) {
                        this.dealOneOffAdditionalOffer(sceneInstId, tableValue, feeOfferInst);
                    }
                }
                tableValueList.add(tableValue);
            }
        });
        String Feeflag="0";
        for (String value : feeArray) {
            countFee = StrTools.numAdd(countFee,value);
        }
        List<DcPublic>  feeDcList=DcPublicCache.get("20211027001");
        if(KiteListUtils.isNotEmpty(feeDcList)&&feeDcList.get(0).getPkey().contains(catId)){
            BigDecimal countFeeBd = new BigDecimal(countFee);
            BigDecimal pcodeBd = new BigDecimal(feeDcList.get(0).getPcode());
            if(countFeeBd.compareTo(pcodeBd)==1){
                Feeflag="1";
            }
        }
        Map tableStatisticsFeeAttr = new HashMap();
        tableStatisticsFeeAttr.put("tableCol", tableColList);
        tableStatisticsFeeAttr.put("tableValue", tableValueList);
        tableStatisticsFeeAttr.put("countFee", countFee);
        tableStatisticsFeeAttr.put("Feeflag", Feeflag);
        if(KiteStringUtils.isEqual(feeTypeCode, "2")) {
            additionalOfferModuleVO.setTableStatisticsChargeFeeAttr(tableStatisticsFeeAttr);
        } else {
            additionalOfferModuleVO.setTableStatisticsFeeAttr(tableStatisticsFeeAttr);
        }
    }

    /**
     * 存量资费标准资费统一展示成N/A
     * @param tableValue
     * @param feeOfferInst
     * @param key
     */
    public void handleStandardFee(Map tableValue, KiteOfferInst feeOfferInst, String key) {
        if (!ActionType.A.equals(feeOfferInst.getActionType()) && KiteStringUtils.equals(key, LocalKeyConsts.STANDARD_MONTHLY_RENT)) {
            tableValue.put(key, "N/A");
        }
    }

    private void dealOneOffAdditionalOffer(String sceneInstId, Map tableValue, KiteOfferInst feeOfferInst) {
        tableValue.remove("cancelOfferInst");
        //1、签订、重提、不允许新增、修改、删除资费
        if (!CuccPosServiceUtils.showAndEditOneOffAddionalOffer(sceneInstId)) {
            tableValue.remove("modOfferInst");
            tableValue.remove("delOfferInst");
            return;
        }
        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        // 起租环节可以修改趸交资费的开始时间
        if (KiteStringUtils.isEqual("OrderStartRent", nodeCode) ) {
            if (KiteStringUtils.isEqual(ActionType.A.name(), feeOfferInst.getActionType().name())) {
                tableValue.remove("delOfferInst");
                return;
            }
            else {
                tableValue.remove("modOfferInst");
                tableValue.remove("delOfferInst");
                return;
            }
        }
        //2、未生效的趸交资费不允许修改或删除
        //生效时间
        KiteAttr starteDateKiteAttr = feeOfferInst.getAttr(LocalKeyConsts.STARTING_DATE_FIELD_NAME);
        if (!ActionType.A.name().equals(feeOfferInst.getActionType().name()) && Objects.nonNull(starteDateKiteAttr) &&
            DateFormatUtils.compareDate(starteDateKiteAttr.getValue(), DateFormatUtils.getFormatedDateTime(), DateFormatUtils.DATE_TIME_FORMAT) > 0) {
            tableValue.remove("modOfferInst");
            tableValue.remove("delOfferInst");
            return;
        }
        //3、趸交资费,如果是否收取违约金字段有值,并且动作是K,认为是已经做过趸交终止,此时不允许修改失效时间
        //是否收取违约金
        KiteAttr damageFeeSwitchAttr = feeOfferInst.getAttr("210004554");
        if (Objects.nonNull(damageFeeSwitchAttr) && KiteStringUtils.isNotEmpty(damageFeeSwitchAttr.getValue())
            && ActionType.K.name().equals(feeOfferInst.getActionType().name())) {
            tableValue.remove("modOfferInst");
            return;
        }
    }

    public void getTableHeader(List<Map> tableColList, String catId, List<String> feeDescribeFieldList) {
        List<DcPublic> dcpublicList = DcPublicCache.getByPkey("20210204", "feeTableHead");
        DcPublic collect = getDcpubliBinaryOperator(dcpublicList, catId);
        if (Objects.isNull(collect)) {
            Map col = new HashMap();
            col.put("dataIndex", "name");
            col.put("title", "资费名称");
            tableColList.add(col);
            Map col1 = new HashMap();
            col1.put("dataIndex", "feeDescribe");
            col1.put("title", "资费描述");
            tableColList.add(col1);
            Map col2 = new HashMap();
            col2.put("dataIndex", "200000172");
            col2.put("title", "生效时间");
            tableColList.add(col2);
            Map col3 = new HashMap();
            col3.put("dataIndex", "200000173");
            col3.put("title", "失效时间");
            tableColList.add(col3);
            Map col4 = new HashMap();
            col4.put("dataIndex", "actionType");
            col4.put("title", "修改标记");
            tableColList.add(col4);
            Map col5 = new HashMap();
            col5.put("dataIndex", "ctrl");
            col5.put("title", "操作");
            tableColList.add(col4);
            feeDescribeFieldList.add("name");//协议月租（元）
            feeDescribeFieldList.add("200000169");//协议月租（元）
            feeDescribeFieldList.add("210004920");//协议价格（元）
            feeDescribeFieldList.add("200000170");//首月收取方式
            feeDescribeFieldList.add("200000171");//末月收取方式
        }
        else {
            String codea = collect.getCodea();
            String codeb = collect.getCodeb();
            if (KiteStringUtils.isNotEmpty(codea)) {
                String[] tablecode = codea.split(",");
                for (int i = 0; i < tablecode.length; i++) {
                    String[] tableHead = tablecode[i].split("\\|");
                    if (tableHead.length <2) {
                        continue;
                    }
                    Map col = new HashMap();
                    col.put("dataIndex", tableHead[0]);
                    col.put("title", tableHead[1]);
                    tableColList.add(col);
                }
            }
            if (KiteStringUtils.isNotEmpty(codeb)) {
                String[] describeField = codeb.split(",");
                for (int i = 0; i < describeField.length; i++) {
                    feeDescribeFieldList.add(describeField[i]);
                }
            }
        }
    }

    public void getStatisticsTableHeader(List<Map> tableColList1, String catId) {
        List<DcPublic> dcpublicList = DcPublicCache.getByPkey("202107131258", "statisticsTableHead");
        DcPublic collect = getDcpubliBinaryOperator(dcpublicList, catId);
        if (Objects.isNull(collect)) {
            Map col = new HashMap();
            col.put("dataIndex", "name");
            col.put("title", "资费项目类型");
            tableColList1.add(col);
            Map col1 = new HashMap();
            col1.put("dataIndex", "200001354");
            col1.put("title", "标准资费");
            tableColList1.add(col1);
            Map col2 = new HashMap();
            col2.put("dataIndex", "200000169");
            col2.put("title", "收入");
            tableColList1.add(col2);
            Map col3 = new HashMap();
            col3.put("dataIndex", "off");
            col3.put("title", "优惠（OFF）");
            tableColList1.add(col3);
        }
        else {
            String codea = collect.getCodea();
            if (KiteStringUtils.isNotEmpty(codea)) {
                String[] tablecode = codea.split(",");
                for (int i = 0; i < tablecode.length; i++) {
                    String[] tableHead = tablecode[i].split("\\|");
                    if (tableHead.length <2) {
                        continue;
                    }
                    Map col = new HashMap();
                    col.put("dataIndex", tableHead[0]);
                    col.put("title", tableHead[1]);
                    tableColList1.add(col);
                }
            }
        }
    }


    private DcPublic getDcpubliBinaryOperator(List<DcPublic> dcpublicList, String catId) {
        if (KiteListUtils.isEmpty(dcpublicList)) {
            return null;
        }
        DcPublic result = dcpublicList.stream().filter(dcpublic -> KiteStringUtils.isEqual(dcpublic.getPcode(), catId)).findFirst().orElse(null);
        if (Objects.isNull(result)) {
            result = dcpublicList.stream().filter(dcpublic -> KiteStringUtils.isEqual(dcpublic.getPcode(), "-1")).findFirst().orElse(null);
        }
        return result;
    }

    public String getValue (KiteAttr kiteAttr) {
        if (Objects.nonNull(kiteAttr)) {
            String value = KiteStringUtils.isEmpty(kiteAttr.getValue()) ?
                (KiteStringUtils.isEmpty(kiteAttr.getDefaultValue()) ? "" : kiteAttr.getDefaultValue()) :
                kiteAttr.getValue();
            List<KiteAttrValue> attrValues = kiteAttr.getAttrValues();
            if (KiteListUtils.isNotEmpty(attrValues)) {
                String valueId = value;
                KiteAttrValue kiteAttrValue = attrValues.stream().filter(attrValue -> KiteStringUtils.equals(valueId, attrValue.getAttrValue())).findFirst().orElse(new KiteAttrValue());
                value = Optional.ofNullable(kiteAttrValue.getAttrValueName()).orElse("");
            }
            return value;
        }

        return "";
    }

    // 按照生效时间进行排序
    public static void sortKitePosFeeList(List<KiteOfferInst> fees) {
        Collections.sort(fees, new Comparator<KiteOfferInst>() {

            @Override
            public int compare(KiteOfferInst o1, KiteOfferInst o2) {

                List<KiteAttr> OfferVO1 = o1.listAttrs();
                KiteAttr offerPosAttrO1 = OfferVO1.stream().filter(offerAttr -> KiteStringUtils.isEqual(offerAttr.getFieldName(), "200000172")).findFirst().orElse(new KiteAttr());
                String o1EffDate = offerPosAttrO1.getValue();
                List<KiteAttr> OfferVO2 = o2.listAttrs();
                KiteAttr offerPosAttrO2 = OfferVO2.stream().filter(offerAttr -> KiteStringUtils.isEqual(offerAttr.getFieldName(), "200000172")).findFirst().orElse(new KiteAttr());
                String o2EffDate = offerPosAttrO2.getValue();

                if (KiteStringUtils.isEmpty(o1EffDate)) {
                    o1EffDate = DateFormatUtils.formatDate(DateFormatUtils.DEFAULTPATTERN);
                }
                if (KiteStringUtils.isEmpty(o2EffDate)) {
                    o2EffDate = DateFormatUtils.formatDate(DateFormatUtils.DEFAULTPATTERN);
                }
                return DateFormatUtils.compareDate(o1EffDate, o2EffDate,  DateFormatUtils.DEFAULTPATTERN);
            }
        });
    }

    //根据销售品ID进行排序
    public static void sortOfferList(List<KiteOfferInst> fees) {
        Collections.sort(fees, new Comparator<KiteOfferInst>() {

            @Override
            public int compare(KiteOfferInst o1, KiteOfferInst o2) {
                return o1.getOfferId().compareTo(o2.getOfferId());//根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数
            }
        });
    }

    /**
     * 五大双线 + 五大双线落地产品分类ID + 政务云
     * @return
     */
    public static String[] getCateIdForDoubleLine() {
        // 五大双线落地产品分类ID
        String cateIdStr = Optional.ofNullable(ProdCateUtil.getSingleCateId("WDSXLD")).orElse("");
        // 五大双线分类ID
        List<String> cateIds = ProdCateUtil.getDoubleLineCateId();
        StringBuffer sb = new StringBuffer(cateIdStr);
        if (KiteListUtils.isNotEmpty(cateIds)) {
            cateIds.forEach(cateId -> {
                sb.append(",").append(cateId);
            });
        }
        // 政务云分类ID
        List<String> zwyCateIds = ProdCateUtil.getZwyCateId();
        if (KiteListUtils.isNotEmpty(zwyCateIds)) {
            zwyCateIds.forEach(cateId -> {
                sb.append(",").append(cateId);
            });
        }
        return sb.toString().split(",");
    }
    /**
     * 政务云
     * @return
     */
    public static String[] getCateIdForZWY() {
        String cateIds = "";
        List<String> zwyCate = ProdCateUtil.getCateIdByCode("ZWY");
        StringBuffer sb = new StringBuffer(cateIds);
        if (KiteListUtils.isNotEmpty(zwyCate)) {
            zwyCate.forEach(cateId -> {
                sb.append(",").append(cateId);
            });
        }
        return sb.toString().split(",");
    }

    /**
     * 是否显示资费统计配置
     */
    public static boolean ifShowFeeStatistics(String cateId, String serviceOfferId) {
        List<DcPublic> dcPublicList = DcPublicCache.getByPkey("2108161001", "SHOW_ZFTJ");
        if(KiteListUtils.isEmpty(dcPublicList)) {
            return false;
        }

        return dcPublicList.stream().anyMatch(dcPublic -> {
            String codea = Optional.ofNullable(dcPublic.getCodea()).orElse("");
            String codeb = Optional.ofNullable(dcPublic.getCodeb()).orElse("");

            return ("-1".equals(codea) || KiteStringUtils.equalsAny(cateId, codea.split(",")))
                && ("-1".equals(codeb) || KiteStringUtils.equalsAny(serviceOfferId, codeb.split(",")));
        });
    }

    // 查询附加商品顺序，作为资费的顺序orderId
    private static String getMemberOrderId(List<MemberGoodDTO> memberGoods, String offerId) {
        if(KiteListUtils.isNotEmpty(memberGoods) && KiteStringUtils.isNotEmpty(offerId)) {
            for (int i = 0; i < memberGoods.size(); i++) {
                if(KiteStringUtils.isEqual(offerId, memberGoods.get(i).getGoodsSku())) {
                    return String.valueOf(i+100);
                }
            }
        }
        return null;
    }

    //获取能被分组的资费信息
    private String feeProdIsToGroup(KiteOfferInst KiteOfferInst) {
        StringBuffer feeProductCodes=new StringBuffer();
        Map goodsInfo = CuccOfferOriginalInfoCache.get(KiteOfferInst.getSpecId());
        if (KiteMapUtils.isEmpty(goodsInfo)) {
            goodsInfo = goodsService.queryGoodsByOfferId(KiteOfferInst.getSpecId());
        }
        //资费产品信息
        List<Map<String, Object>> productCategroys = (List<Map<String, Object>>) goodsInfo.get("productCategroy");
        if (KiteListUtils.isNotEmpty(productCategroys)) {
            for (Map<String, Object> productCategroy : productCategroys) {
                if ("true".equals(KiteMapUtils.getString(productCategroy, "isShowGroup"))) {
                    List<Map<String, Object>> products = (List<Map<String, Object>>) productCategroy.get("products");
                    if (KiteListUtils.isNotEmpty(products)) {
                        for (Map<String, Object> additionalofferMap : products) {
                            feeProductCodes.append(KiteMapUtils.getString(additionalofferMap, "productCode")+",");
                        }
                    }
                }
            }
        }
        return feeProductCodes.toString();
    }
    //处理能被分组的资费信息
    private  List<Map> addTableFeeValueAttrGroup(List<Map> tableValueList) {
        List<Map> tableValueGroupList = new ArrayList();
        if(KiteListUtils.isNotEmpty(tableValueList)){
            List<Map<String, Object>> tableValueShowGroupByTime = new ArrayList();
            List<Map<String, Object>> tableValueShowGroupByEffectMode = new ArrayList();

            List<Map<String, Object>>  ableValueisUnShowGroup= new ArrayList();
            for (Map<String, Object> tableValueMap : tableValueList) {
                if ("true".equals(tableValueMap.get("isShowGroup"))) {
                    String effectMode=KiteMapUtils.getString(tableValueMap, "200000174");
                    if(KiteStringUtils.isNotEmpty(effectMode) && "110006909".equals(effectMode)){
                        tableValueShowGroupByEffectMode.add(tableValueMap);
                    } else {
                        //不是以起租时间生效资费信息
                        tableValueShowGroupByTime.add(tableValueMap);
                    }
                } else {
                    ableValueisUnShowGroup.add(tableValueMap);
                }
            }
            //可进行分组的资费进行分组处理
            if(KiteListUtils.isNotEmpty(tableValueShowGroupByTime) || KiteListUtils.isNotEmpty(tableValueShowGroupByEffectMode)){
                sortGroupFeeList(tableValueShowGroupByTime);
                Map<String, List<Map<String, Object>>> groupMap = tableValueShowGroupByTime.stream().
                    collect(Collectors.groupingBy(e -> e.get("200000172") + "_"+ e.get("200000173"),LinkedHashMap::new,Collectors.toList()));

                //生效模式为起租时间生效的模式
                if(KiteListUtils.isNotEmpty(tableValueShowGroupByEffectMode)){
                    groupMap.put("EffectiveMode",tableValueShowGroupByEffectMode);
                }
                //计算分组的费用总
                List list = new ArrayList();
                Iterator iter = groupMap.entrySet().iterator(); // 获得map的Iterator
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    list.add(entry.getKey());
                }
                if(KiteListUtils.isNotEmpty(list)){
                    for (int i = 0; i <list.size() ; i++) {
                        Map<String, Object> attrValueGroupWithCount = new HashMap();
                        String countFee = "0";
                        List<Map<String, Object>> groupMapList = groupMap.get(list.get(i));
                        if(KiteListUtils.isNotEmpty(groupMapList)){
                            for (int j = 0; j < groupMapList.size(); j++) {
                                if(KiteMapUtils.isNotEmpty(groupMapList.get(j))){
                                    if( groupMapList.get(j).containsKey("200000169")){
                                        String rentAgreement = MapUtils.getString(groupMapList.get(j), "200000169");
                                        if(KiteStringUtils.isNotEmpty(rentAgreement)){
                                            countFee = StrTools.numAdd(countFee,rentAgreement);
                                        }
                                    }
                                }
                            }
                            attrValueGroupWithCount.put (list.get(i).toString(),groupMapList);
                            BigDecimal count = new BigDecimal(countFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                            attrValueGroupWithCount.put("countFee",count);
                            tableValueGroupList.add(attrValueGroupWithCount);
                        }
                    }
                }
            }
            tableValueGroupList.addAll(ableValueisUnShowGroup);

        }
        return  tableValueGroupList;
    }

    // Map按照生效时间进行排序
    public static void sortGroupFeeList(List<Map<String, Object>> tableValueList) {
        Collections.sort(tableValueList, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map o1, Map o2) {
                String o1EffDate=KiteMapUtils.getString(o1, "200000172");
                String o2EffDate=KiteMapUtils.getString(o2, "200000172");
                if (KiteStringUtils.isEmpty(o1EffDate)) {
                    o1EffDate = DateFormatUtils.formatDate(DateFormatUtils.DEFAULTPATTERN);
                }
                if (KiteStringUtils.isEmpty(o2EffDate)) {
                    o2EffDate = DateFormatUtils.formatDate(DateFormatUtils.DEFAULTPATTERN);
                }
                return DateFormatUtils.compareDate(o1EffDate, o2EffDate,  DateFormatUtils.DEFAULTPATTERN);

            }
        });
    }
}


